package com.zlp.boot1.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: zhulaiping
 * @Date: 2021/11/1 14:08
 */
@WebServlet("/cookie2")
public class CookieDemo2 extends HttpServlet {
    int count = 0;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            writer.write("Cookie name: "+cookies[0].getName()+"\r\n");
            writer.write("Cookie value: "+cookies[0].getValue()+"\r\n");
            writer.write("Max Age: "+cookies[0].getMaxAge()+"\r\n");
            if(cookies[0].getValue().equals("tom")){
                cookies[0].setValue("jack");
            }else if(cookies[0].getValue().equals("jack")){
                cookies[0].setMaxAge(0);
            }
            resp.addCookie(cookies[0]);
        }else {
            writer.println("No cookie");
            Cookie cookie = new Cookie("username", "tom");
            cookie.setMaxAge(60*60);
            resp.addCookie(cookie);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        doGet(req,resp);
    }
}
